<template>
  <div class="container">
    <div class="tools">
      <el-button type="success" @click="dialogTableVisible = true">新建答题卡识别方案</el-button>
      <el-button type="primary" @click="goSheet()">新建答题卡</el-button>
    </div>

    <div class="container_table">
      <el-table
          :data="tableData"
          stripe
          :header-cell-style="{height: '54px',background: '#f5f5f5',fontSize: '14px', color: '#3D3D3D'}"
          max-height="500px"
          style="width: 100%;">


        <el-table-column
            label="答题卡"
            width="">
          <template slot-scope="{row}">
            <!--          <el-image :preview-src-list="row.imgs" v-for="(img, index) in row.imgs" :key="img" :src="img"
                                style="height: 200px"></el-image>-->
            <el-image lazy v-if="row.finish === 'ok'" :preview-src-list="[row.templateImg]" :src="row.templateImg"
                      style="height: 200px"></el-image>
            <template v-else>
              <el-image lazy v-for="(item,i) in row.imgs" :key="item.url" :preview-src-list="[item.url]" :src="item.url"
                        style="height: 200px"></el-image>
            </template>


          </template>
        </el-table-column>
        <el-table-column
            label="模板名称"
            prop="templateName"
            width="">
        </el-table-column>
        <el-table-column
            label="考号"
            prop="studentIdType"
            width="">
          <template slot-scope="{row}">
            <el-tag>{{ row.studentIdType === 'pan' ? '填涂' : '其他' }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column
            label="年级"
            prop="gradeName"
            width="">
        </el-table-column>

        <el-table-column
            label="科目"
            prop="subjectName"
            width="">
        </el-table-column>
        <el-table-column
            label="启用"
            prop="enabled"
            width=""
        >
          <template slot-scope="{row}">
            <el-switch
                v-model="row.enabled"
                @change="changeEnabled(row)"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            prop="finish"
            label="完成状态"
            width="">
          <template slot-scope="{row}">
            <el-tag :type="row.finish === 'ok' ? 'success': 'warning'">
              {{
                row.finish === 'ok' ? '已完成' : '未完成'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="200">
          <template slot-scope="scope">

            <el-button @click="goSheet(scope.row.id)" type="text" size="small">答题卡</el-button>
            <el-button @click="toLook(scope.row.id)" type="text" size="small">编辑</el-button>
            <el-button @click="deleteRow(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <el-dialog title="创建" :visible.sync="dialogTableVisible">
      <el-form :model="form">
        <el-form-item label="模板" label-width="80px">
          <el-upload
              ref="upload"
              action="#"
              :file-list="fileList"

              multiple
              :on-change="handleFileChange"
              :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>


          </el-upload>
        </el-form-item>
        <el-form-item v-show="imgs.length > 0" label="已选中图片" label-width="80px">
          <div style="float: left" v-for="(url, urlIndex) in imgs" :key='url'>
            <el-image lazy :src="url.url" :preview-src-list="[url.url]"
                      style="width: 100px;height: 100px"></el-image>
            <p>第{{ urlIndex + 1 }}页</p>
          </div>

          <el-button @click="clearImgs">清空</el-button>
          <el-button v-show="imgs.length > 1" @click="() => {
            let temp = this.imgs[0]
            this.imgs[0] = this.imgs[1]
            this.imgs[1] = temp
            this.imgs = this.imgs.map(item => item)
          }">交换
          </el-button>
        </el-form-item>
        <el-form-item label-width="120px" required label="模板名称">
          <el-input style="width: 200px" v-model="form.templateName" placeholder="请输入模板名称"></el-input>
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="success" @click="handleCreateParse">创建</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {imageUtil} from "@/ImageUtil.js";


export default {
  name: "parent",
  props: ['otherImages'],
  data() {
    return {
      selectScanner:false,
      selectIndex: '',
      scanners:[],
      fileList: [],
      dialogTableVisible: false,
      tableData: [],
      workId: "",
      work: null,
      form: {
        templateName: ''
      },
      imgs: [],
      scanFilePaths: []
    }
  },
  methods: {
    goSheet(parseId) {
      let url = window.origin + "/sheet-front/sheet.html?paperId=" + this.work.paperId;
      if (parseId) {
        url = url + "&parseId=" + parseId
      }
      window.open(url);
    },
    async changeEnabled(row) {

      let res = await this.$api.changeParseEnabled({
        id: row.id,
        enabled: row.enabled ? 1 : 0
      })
      if (res.code !== 200) {
        row.enabled = !row.enabled ? 1 : 0
        return
      }
      await this.queryParseList()
      this.$message.success("修改成功")

    },
    async handleCreateParse() {
      let res = await this.$api.createParse({
        imgs: this.imgs,
        paperId: this.work.paperId,
        templateName: this.form.templateName
      })
      if (res.code !== 200) {
        this.$message.error("创建失败")
        return
      }
      this.queryParseList()
      this.dialogTableVisible = false
    },
    clearImgs() {
      this.imgs = []
    },
    async handleFileChange(file, fileList) {
      if (fileList.length === 0) {
        return
      }
      this.fileList = fileList

      let fileList1 = this.fileList;
      if (fileList1.length !== 0) {
        const length = fileList1.length;
        const imgs = [];
        for (let i = 0; i < length; i++) {
          let fileListElement = fileList1[i];
          let formData = new FormData();
          formData.append("file", fileListElement.raw)
          let res = await this.$api.saveFile(formData)
          if (res.code !== 200) {
            alert("上传文件失败")
            return
          }
          let size = await imageUtil.getSize(res.data.url);
          imgs.push({
            url: res.data.url,
            width: size.width,
            height: size.height
          })

          this.imgs = imgs
        }
        this.fileList = [];
      }
    },
    async handleSourceImgs() {
      let sourceImgs = []
      const loading = this.$fastLoading()
      try {
        try {
          sourceImgs = JSON.parse(window.localStorage.getItem("templateImgs"))
          if (!sourceImgs) {
            return
          }
        } catch (e) {
          return
        } finally {
          window.localStorage.removeItem("templateImgs")
        }
        this.form.templateName = '模板'
        const imgs = []
        for (let i = 0; i < sourceImgs.length; i++) {
          let url = sourceImgs[i]
          let size = await imageUtil.getSize(url);
          imgs.push({
            url: url,
            width: size.width,
            height: size.height
          })
        }
        this.imgs = imgs
        this.dialogTableVisible = true
      } finally {
        loading.close()
      }
    },
    async deleteRow(parseId) {
      let res = await this.$api.deleteTemplate({
        id: parseId
      })
      if (res.code !== 200) {
        this.$error('删除失败')
        return
      }
      this.$success('删除成功')
      this.queryParseList()
    },
    toLook(parseId) {
      let url = window.origin + "/sheet-front/index.html?"
      if (parseId) {
        url = url + "&parseId=" + parseId
      }
      window.open(url);
      // this.$router.push({path: '/paper-parse-template/set_student_id', query: {parseId: parseId, workId: this.work.id}})
    },
    async queryWork() {

      let res = await this.$api.workOne({
        id: this.workId
      })
      if (res.code !== 200) {
        this.$message.warning(res.message)

        return
      }
      this.work = res.data

    },
    async queryParseList() {
      let loading = this.$fastLoading();
      try {
        let res = await this.$api.parseList({
          paperId: this.work.paperId
        })
        if (res.code !== 200) {
          this.$message.warning(res.message)
          return;
        }
        this.tableData = res.data.map(item => {
          item.templateImg = this.$api.getTemplateUrl(item.id)
          return item
        })
      } finally {
        loading.close()
      }
    }
  },
  created() {
    this.workId = this.$route.query.workId
  },
  async mounted() {
    await this.queryWork()
    await this.queryParseList()
    await this.handleSourceImgs()
  },
  watch: {}
}
</script>

<style scoped type="less">
.container {
  padding: 31px 34px;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  .tools {
    .el-button {
      background: #4187FF;
    }
  }
  .container_table {
    margin-top: 16px;
  }
  .view_container {
    height: calc(100% - 77px);
    width: 100%;
    overflow: auto;

    cropper-selection {
      outline: rgb(236 26 26) solid 2px;
    }

    cropper-selection[active] {
      outline: rgb(50, 208, 37) solid 2px;
    }

    .button__container {
      padding-bottom: 10px;
      box-sizing: border-box;
    }

    cropper-selection.show_content > * {
      visibility: visible;
    }

    .disabled_resize > cropper-handle[action='n-resize'],
    .disabled_resize > cropper-handle[action='e-resize'],
    .disabled_resize > cropper-handle[action='s-resize'],
    .disabled_resize > cropper-handle[action='w-resize'],
    .disabled_resize > cropper-handle[action='ne-resize'],
    .disabled_resize > cropper-handle[action='nw-resize'],
    .disabled_resize > cropper-handle[action='se-resize'],
    .disabled_resize > cropper-handle[action='sw-resize'] {
      display: none;
    }

    .choice__item div, .choice__student_id div {
      visibility: visible;
      z-index: 1;
    }

    .choice__item cropper-handle[action='move'], .choice__student_id cropper-handle[action='move'] {
      /*z-index: 10;*/
    }
  }
}

</style>